package com.xpsoft.oa.workflow.event;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.listener.EventListener;
import org.jbpm.api.listener.EventListenerExecution;
import org.jbpm.api.model.OpenProcessInstance;

import com.xpsoft.core.util.AppUtil;
import com.xpsoft.core.util.ContextUtil;
import com.xpsoft.oa.model.flow.ProcessRun;
import com.xpsoft.oa.model.produce.MaterialPurchase;
import com.xpsoft.oa.model.system.AppUser;
import com.xpsoft.oa.service.flow.ProcessRunService;
import com.xpsoft.oa.service.produce.MaterialPurchaseService;
import com.xpsoft.oa.service.project.ProjectService;

public class MaterialPurchaseFinishListener implements EventListener{
	private Log logger=LogFactory.getLog(MaterialPurchaseFinishListener.class);
	@Override
	public void notify(EventListenerExecution execution) throws Exception {
		//获取表单参数
		OpenProcessInstance pi=execution.getProcessInstance();
		String proId = (String)pi.getVariable("materialPurchase.project.id");
		String planNo = (String)pi.getVariable("materialPurchase.planNo");
		String quality = (String)pi.getVariable("materialPurchase.quality");
		String dataList = (String)pi.getVariable("materialPurchase.dataList");
		Date planDate = (Date)pi.getVariable("materialPurchase.planDate");
		
		MaterialPurchase materialPurchase = new MaterialPurchase();
		materialPurchase.setCreateTime(new Date());
		materialPurchase.setCreateUser(ContextUtil.getCurrentUser());
		materialPurchase.setPlanNo(planNo);
		materialPurchase.setPlanDate(planDate);
		materialPurchase.setQuality(quality);
		if(StringUtils.isNotBlank(proId)){
			ProjectService projectService = (ProjectService)AppUtil.getBean("projectService");
			materialPurchase.setProject(projectService.get(Long.valueOf(proId)));
		}
		
		ProcessRunService processRunService=(ProcessRunService)AppUtil.getBean("processRunService");
		ProcessRun processRun=processRunService.getByExeId(pi.getId());
		materialPurchase.setProcessRunId(processRun.getRunId());
		
		MaterialPurchaseService materialPurchaseService = (MaterialPurchaseService)AppUtil.getBean("materialPurchaseService");
		materialPurchaseService.saveMaterialPurchase(materialPurchase, dataList);
		
		
		//获取流程发起者对象
		AppUser flowStartUser=(AppUser)execution.getProcessInstance().getVariable("flowStartUser");
	
		//所有参与流程的都发消息
		AppUtil.sendSysShortMsg(execution.getProcessInstance().getId(), flowStartUser);
	}

}
